﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ChatClient
{
    public delegate void ResponseReceivedEventHandler(object sender, ResponseReceivedEventArgs e);

    public class ResponseReceivedEventArgs : EventArgs
    {
        // True if an error occured, False otherwise
        public bool isError { get; set; }

        // If there was an erro, this will contain the error message, data otherwise
        public string response { get; set; }
    }

    class ConnectServer
    {
        const int TIMEOUT = 3000;
        int bufflength = 1024;

        internal event ResponseReceivedEventHandler ResponseReceived;

        //socket
        private Socket _client_sock;
        //Thread listen;
        SocketAsyncEventArgs socketEventArg;
        //luu data
        static String dataIn = String.Empty;
        //private string servername = "192.168.73.1";
        private string servername = "Bvnkame";
        private int port = 13001;
        DnsEndPoint hostEntry;
        string dataFromServer = "";

        public ConnectServer()
        {

        }

        public void connectToServer()
        {
            socketEventArg = new SocketAsyncEventArgs();

            hostEntry = new DnsEndPoint(servername, port);

            _client_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(Connect_Completed);
            socketEventArg.RemoteEndPoint = hostEntry;

            socketEventArg.UserToken = _client_sock;

            try
            {
                _client_sock.ConnectAsync(socketEventArg);
            }
            catch (SocketException ex)
            {
                throw new SocketException((int)ex.ErrorCode);
            }
        }

        public void SendData(string data)
        {
            if (String.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentNullException("data");
            }

            dataIn = data;

            //byte[] buffer = Encoding.UTF8.GetBytes(dataIn + "<EOF>");
            //socketEventArg.SetBuffer(buffer, 0, buffer.Length);
            //_client_sock.SendAsync(socketEventArg);

        }

        void Connect_Completed(object sender, SocketAsyncEventArgs e)
        {
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.Connect:
                    ProcessConnect(e);
                    break;
                case SocketAsyncOperation.Receive:
                    ProcessReceive(e);
                    break;
                case SocketAsyncOperation.Send:
                    ProcessSend(e);
                    break;
                default:
                    throw new Exception("Invalid operation completed");
            }
        }

        void ProcessConnect(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                byte[] buffer = Encoding.UTF8.GetBytes("Hi server<EOF>");
                e.SetBuffer(buffer, 0, buffer.Length);
                _client_sock.SendAsync(e); 
            }
            else
            {
                ResponseReceivedEventArgs args = new ResponseReceivedEventArgs();
                args.response = e.SocketError.ToString();
                args.isError = true;
                OnResponseReceived(args);

            } 
        }

        void ProcessReceive(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                if (e.BytesTransferred > 0)
                {
                    string data = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
                    dataFromServer += data;
                    if (dataFromServer.IndexOf("<EOF>") > -1)
                    {
                        dataFromServer = dataFromServer.Replace("<EOF>", "");
                        if (!dataFromServer.Equals("null"))
                        {
                            // Respond to the client in the UI thread to tell him that data was received
                            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                ResponseReceivedEventArgs args = new ResponseReceivedEventArgs();
                                args.response = dataFromServer;
                                OnResponseReceived(args);
                            });
                        }

                        if (!dataIn.Equals(""))
                        {
                            byte[] buffer = Encoding.UTF8.GetBytes(dataIn + "<EOF>");
                            e.SetBuffer(buffer, 0, buffer.Length);
                            dataIn = "";
                        }
                        else
                        {
                            byte[] buffer = Encoding.UTF8.GetBytes("null<EOF>");
                            e.SetBuffer(buffer, 0, buffer.Length);
                        }
                        Thread.Sleep(300);
                        _client_sock.SendAsync(e);
                        dataFromServer = "";
                    }
                    else
                    {
                        _client_sock.ReceiveAsync(e);
                    }
                }
            }
            else
            {
                throw new SocketException((int)e.SocketError);
            }
        }
        
        void ProcessSend(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                _client_sock.ReceiveAsync(e);
            }
            else
            {
                ResponseReceivedEventArgs args = new ResponseReceivedEventArgs();
                args.response = e.SocketError.ToString();
                args.isError = true;
                OnResponseReceived(args);
            } 
        }

        protected void OnResponseReceived(ResponseReceivedEventArgs e)
        {
            if (ResponseReceived != null)
                ResponseReceived(this, e);
        }
    }

}
